const Router = require('koa-router');
const mysql = require('mysql2/promise');
const bodyParser = require('koa-bodyparser');
const {koaBody} = require('koa-body');
const fs = require('fs');
const path = require('path');
const router = new Router();

router.use(bodyParser());

// 定义数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'student',
};

// 上传图片接口
router.post('/upload-files', koaBody({ multipart: true }), async (ctx) => {
  try {
    const { files } = ctx.request;
    const file = files?.file; // 获取上传的文件
    console.log('files:', file);

    if (!file) {
      ctx.status = 400;
      ctx.body = { code: 400, message: '未找到上传文件' };
      return;
    }

    // 定义保存图片的目录
    const uploadDir = path.join(__dirname, 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir); // 如果目录不存在，则创建
    }

    // 生成新的文件名并保存文件
    const fileName = `${Date.now()}_${file.originalFilename}`;
    const filePath = path.join(uploadDir, fileName);
     
    const reader = fs.createReadStream(file.filepath);
    const writer = fs.createWriteStream(filePath);
    reader.pipe(writer);

    // 将文件路径存入数据库
    const connection = await mysql.createConnection(dbConfig);
    const query = `
      INSERT INTO uploaded_files (file_name, file_path, upload_time)
      VALUES (?, ?, NOW())
    `;
    await connection.execute(query, [fileName, filePath]);
    await connection.end();


    // 返回响应
    ctx.body = {
      code: 200,
      message: '文件上传成功',
      data: {
        fileName,
        filePath,
      },
    };
  } catch (error) {
    console.error('上传失败:', error);
    ctx.status = 500;
    ctx.body = { code: 500, message: '内部服务器错误' };
  }
});

// 查询图片信息接口
router.get('/uploaded-files', async (ctx) => {
  try {
    const connection = await mysql.createConnection(dbConfig);

    // 查询所有上传的文件信息
    const [rows] = await connection.execute(
      'SELECT id, file_name, file_path, upload_time FROM uploaded_files'
    );
    await connection.end();

    ctx.body = {
      code: 200,
      message: '查询成功',
      data: rows,
    };
  } catch (error) {
    console.error('查询失败:', error);
    ctx.status = 500;
    ctx.body = { code: 500, message: '内部服务器错误' };
  }
});

module.exports = router;
